package cn.wizzer.app.web.modules.controllers.user;

import cn.wizzer.app.user.modules.models.UserExchange;
import cn.wizzer.app.user.modules.models.enums.ExchangeEnum;
import cn.wizzer.app.user.modules.services.account.ExchangeService;
import cn.wizzer.app.web.commons.filter.ApiTokenFilter;
import cn.wizzer.app.web.commons.ulog.annotation.ULog;
import cn.wizzer.framework.base.Result;
import cn.wizzer.framework.filter.ParamFilter;
import com.alibaba.dubbo.config.annotation.Reference;
import io.swagger.annotations.Api;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Times;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.annotation.*;

@Api(value = "/api/user/exchange", tags = "兑换商品")
@IocBean
@At("/api/user/exchange")
public class ApiUserExchangeController {
    @Inject
    @Reference(retries = 0)
    private ExchangeService exchangeService;


    /**
     * 兑换商品（下单）
     *
     * @param userExchange UserExchange
     * @return Object
     */
    @At("/doExchange")
    @Ok("json")
    @Filters({@By(type = ApiTokenFilter.class), @By(type = ParamFilter.class)})
    @ULog(tag = "用户兑换商品", msg = "商品: ${userExchange.goodsId}")
    public Object doExchange(@Param("..") UserExchange userExchange) {
        String appid = Mvcs.getReq().getHeader("appid");
        userExchange.setUserId(appid);
        exchangeService.add(userExchange);
        return Result.success();
    }

    /**
     * 兑换记录列表(分页)
     *
     * @param pageNumber int
     * @param pageSize   int
     * @return Object
     */
    @At("/list")
    @Ok("json")
    @Filters({@By(type = ApiTokenFilter.class), @By(type = ParamFilter.class)})
    public Object list(@Param("pageNumber") int pageNumber,
                       @Param("pageSize") int pageSize,
                       @Param("status") ExchangeEnum status) {
        return Result.success().addData(exchangeService.listPage(pageNumber, pageSize, status, Mvcs.getReq().getHeader("appid")));
    }

    /**
     * 查询所有类型
     *
     * @return Object
     */
    @At("/statusList")
    @Ok("json")
    public Object statusList() {
        return Result.success().addData(ExchangeEnum.toList());
    }

    /**
     * 确认收货
     *
     * @return Object
     */
    @At("/confirm")
    @Ok("json")
    @Filters({@By(type = ApiTokenFilter.class), @By(type = ParamFilter.class)})
    public Object confirm(String id) {
        UserExchange userExchange = exchangeService.fetch(id);
        if(!userExchange.getUserId().equals(Mvcs.getReq().getHeader("appid"))){
            return Result.error("确认收货失败，这不是你的记录");
        }
        if(!userExchange.getStatus().equals(ExchangeEnum.DELIVERY)){
            return Result.error("订单不是已发货状态，无法确认收货");
        }
        exchangeService.update(Chain.make("status",ExchangeEnum.FINISHED)
                .add("opAt", Times.getTS()), Cnd.where("id","=",id));
        return Result.success();
    }

}
